package com.xuelang.pipeline.app.project.converter;

import com.xuelang.hiforce.base.utils.bean.SpringApplicationContextHolder;
import com.xuelang.jadp.client.sys.dto.UserInfoDTO;
import com.xuelang.pipeline.app.project.ProjectTypeService;
import com.xuelang.pipeline.client.common.constant.Constant;
import com.xuelang.pipeline.client.project.dto.ProjectDTO;
import com.xuelang.pipeline.client.project.dto.ProjectTypeDTO;
import com.xuelang.pipeline.domain.project.Project;
import com.xuelang.sys.app.sys.UserManagerService;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;

import java.util.Objects;

/**
 * <p>项目实体至DTO转换器</p>
 *
 * @author : yixin.lys
 * @date : 2024-09-03 11:09
 **/
@Mapper
public interface ProjectToDTOConverter {

    ProjectToDTOConverter INSTANCE = Mappers.getMapper(ProjectToDTOConverter.class);

    /**
     * 转为DTO
     * @param entity
     * @return
     */
    ProjectDTO toDTO(Project entity);

    /**
     *
     * @param dto
     * @return
     */
    Project fromDTO(ProjectDTO dto);


    @AfterMapping
    default void afterMappingToDTO(Project source, @MappingTarget ProjectDTO target) {
        if (source != null && StringUtils.isNotBlank(source.getCreatorId())) {
            UserManagerService userManagerService = SpringApplicationContextHolder.getSpringBean(UserManagerService.class);
            UserInfoDTO user = userManagerService.getUserById(source.getCreatorId());
            if (Objects.nonNull(user)) {
                target.setCreator(user.getRealName());
            }else{
                target.setCreator(Constant.UNKNOWN_USER);
            }
        }

        if (source != null && Objects.nonNull(source.getProjectType())) {
            ProjectTypeService projectTypeService = SpringApplicationContextHolder.getSpringBean(ProjectTypeService.class);
            ProjectTypeDTO projectType = projectTypeService.findProjectTypeById(source.getProjectType());
            if (Objects.nonNull(projectType)) {
                target.setProjectTypeName(projectType.getName());
            }else{
                target.setProjectTypeName(Constant.UNKNOWN_PROJECT_TYPE);
            }
        }
    }
}
